package com.ezcolour.ticket.web.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ezcolour.ticket.base.BaseController;
import com.ezcolour.ticket.base.BaseException;
import com.ezcolour.ticket.bean.JwtProperties;
import com.ezcolour.ticket.common.util.CrawlerUtil;
import com.ezcolour.ticket.model.VocalBean;
import com.ezcolour.ticket.support.BizExceptionEnum;
import com.ezcolour.ticket.util.JwtTokenUtil;
import com.ezcolour.ticket.web.global.GlobalCache;
import com.ezcolour.ticket.web.thread.TicketThread;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.CookieStore;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.PoolingClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

/**
 *  抢票
 *
 * @author rhp
 * @date 2017-08-23 9:23
 */
@Controller
@RequestMapping("/web/api")
public class RobWebController extends BaseController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private JwtProperties jwtProperties;



    /**
     * 获取登录token
     */
    @RequestMapping(value = "/token", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> getToken(HttpServletRequest request,String account) {
        Long time = null;
        try{
            DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
            //登录页面cookie
            HttpGet get = new HttpGet("https://secure.damai.cn/login.aspx?ru=http://order.damai.cn/index.aspx?spm=a2o6e.home.0.0.591b48d3jLMGcC");
            HttpResponse indexResponse = client.execute(get);
            HttpEntity entity = indexResponse.getEntity();
            CookieStore cookieStore = client.getCookieStore();
            client.setCookieStore(cookieStore);

            time = new Date().getTime();
            get = new HttpGet("https://fp.fraudmetrix.cn/fp/clear.png?partnerCode=damai&appName=damai_web&tokenId="+time);
            HttpResponse tokenResponse = client.execute(get);

            get = new HttpGet("https://secure.damai.cn/VerifyShow.aspx?_action=QRCode");
            HttpResponse qrcodeResponse = client.execute(get);
            String username = getLoginUserName(request);
            ConcurrentHashMap<String, HttpResponse> qrcodeMap =GlobalCache.user_qrcode.get(username);
            ConcurrentHashMap<String, CookieStore> cookieMap = GlobalCache.user_cookies.get(username);
            if(qrcodeMap==null || qrcodeMap.size()<=0){
                qrcodeMap = new ConcurrentHashMap<String, HttpResponse>();
            }
            if(cookieMap==null || cookieMap.size()<=0){
                cookieMap = new ConcurrentHashMap<String, CookieStore>();
            }
            qrcodeMap.put(account,qrcodeResponse);
            cookieMap.put(account,cookieStore);
            GlobalCache.user_qrcode.put(username,qrcodeMap);
            GlobalCache.user_cookies.put(username,cookieMap);
        }catch (Exception e){
            e.printStackTrace();
        }

        return ResponseEntity.ok(time);
    }

/**
     * 验证是否登录
     */
    @RequestMapping(value = "/verify", method = RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<?> verify(HttpServletRequest request,String account) {
        boolean result = false;
        ConcurrentHashMap<String, CookieStore> cookieMap = GlobalCache.user_login_cookies.get(getLoginUserName(request));
        if(cookieMap==null ||cookieMap.size()<=0 ){
            result = true;
        }else{
            CookieStore cookieStore = cookieMap.get(account);
            if(cookieStore == null){
                result = true;
            }
        }
        return ResponseEntity.ok(true);
    }

    /**
     * 获取二维码
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.GET)
    @ResponseBody
    public void getQrcode(HttpServletResponse response, HttpServletRequest request,String account) {
        try {
            OutputStream outputStream = null;
            try{
                ConcurrentHashMap<String, HttpResponse> qrcodeMap = GlobalCache.user_qrcode.get(getLoginUserName(request));
                HttpResponse qrcodeResponse = qrcodeMap.get(account);
                qrcodeMap.remove(account);
                byte[] bytes = EntityUtils.toByteArray(qrcodeResponse.getEntity());
                response.reset();// 不加这一句的话会出现下载错误
                response.setDateHeader("Expires", 0);
                // Set standard HTTP/1.1 no-cache headers.
                response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
                // Set IE extended HTTP/1.1 no-cache headers (use addHeader).
                response.addHeader("Cache-Control", "post-check=0, pre-check=0");
                // Set standard HTTP/1.0 no-cache header.
                response.setHeader("Pragma", "no-cache");
                // return a jpeg
                response.setContentType("image/jpeg");
                outputStream = response.getOutputStream();

                outputStream.write(bytes);
                outputStream.flush();
            }finally {
                if(outputStream != null){
                    outputStream.close();
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 验证二维码
     */
    @RequestMapping(value = "/qrcode", method = RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<?> checkQrcode(HttpServletRequest request,String token,String account) {
        String code =null;
        CookieStore cookieStore = null;
        String username = getLoginUserName(request);
        try{
            ConcurrentHashMap<String, CookieStore> loginCookieMap = GlobalCache.user_cookies.get(username);
            cookieStore = loginCookieMap.get(account);
            DefaultHttpClient client = new DefaultHttpClient(new PoolingClientConnectionManager());
            HttpPost post = new HttpPost("https://secure.damai.cn/VerifyShow.aspx");
            client.setCookieStore(cookieStore);
            List<NameValuePair> params = Lists.newArrayList();
            params.add(new BasicNameValuePair("_action", "getQRCodeState"));
            params.add(new BasicNameValuePair("token", token));
            post.setEntity(new UrlEncodedFormEntity(params, Consts.UTF_8));
            HttpResponse loginRes = client.execute(post);
            code = EntityUtils.toString(loginRes.getEntity());
            if(code.equals("1")){
                loginCookieMap.remove(account);
                ConcurrentHashMap<String, CookieStore> loginCookie = GlobalCache.user_login_cookies.get(username);
                if(loginCookie == null || loginCookie.size()<=0){
                    loginCookie = new ConcurrentHashMap<String, CookieStore>();
                }
                loginCookie.put(account,client.getCookieStore());
                GlobalCache.user_login_cookies.put(getLoginUserName(request),loginCookie);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return ResponseEntity.ok(code);
    }

    /**
     *
     */
    @RequestMapping(value = "/auto/one", method = RequestMethod.GET)
    public void autoOne(HttpServletResponse response,Long orderId/*,String account*/,String token) {
        System.out.println(token);
        if(token==null || jwtTokenUtil.isTokenExpired(token)) {
            throw new BaseException(BizExceptionEnum.TOKEN_ERROR);
        }
        String username = jwtTokenUtil.getUsernameFromToken(token);
        //获取对应用户对应演唱会bean
        ConcurrentHashMap<Long, VocalBean> ordersMap = GlobalCache.user_vocal.get(username);
        VocalBean vocalBean = ordersMap.get(orderId);
        String vocalId = vocalBean.getProjectId();
        String proId = vocalBean.getPriceId();
        String companyId = vocalBean.getCompanyId();
        String performId = vocalBean.getPerformId();
        Integer number = vocalBean.getNumber();
        long time = new Date().getTime() + 300000;

        while (true){
            long now = new Date().getTime();
            if(now >= time  ){
                break;
            }
            if(CrawlerUtil.getStatu(vocalId,performId,proId)){
                try{
                    String data = "commodity=2|"+proId+"^"+number+"^"+performId+"&cityId="+companyId+"&projectId="+vocalId+"&privilegeId=0"+"&spm=a2o71.selectitem.bottom.dselectsubmit";
                    /*
                    response.setHeader("Cookie",getCookies(username,account));
                    */
                    response.setHeader("Host","m.damai.cn");
                    response.sendRedirect("http://m.damai.cn/damai/trade/index.html?"+data);
                }catch (Exception e){
                    e.printStackTrace();
                }
                break;
            }

        }
    }

    /**
     *
     */
    @RequestMapping(value = "/auto/direct", method = RequestMethod.GET)
    public void autoDirect(HttpServletResponse response,Long orderId/*,String account*/,String token) {
        System.out.println(token);
        if(token==null || jwtTokenUtil.isTokenExpired(token)) {
            throw new BaseException(BizExceptionEnum.TOKEN_ERROR);
        }
        String username = jwtTokenUtil.getUsernameFromToken(token);
        //获取对应用户对应演唱会bean
        ConcurrentHashMap<Long, VocalBean> ordersMap = GlobalCache.user_vocal.get(username);
        VocalBean vocalBean = ordersMap.get(orderId);
        String vocalId = vocalBean.getProjectId();
        String proId = vocalBean.getPriceId();
        String companyId = vocalBean.getCompanyId();
        String performId = vocalBean.getPerformId();
        Integer number = vocalBean.getNumber();
        try{
            String data = "commodity=2|"+proId+"^"+number+"^"+performId+"&cityId="+companyId+"&projectId="+vocalId+"&privilegeId=0"+"&spm=a2o71.selectitem.bottom.dselectsubmit";
            /*
            response.setHeader("Cookie",getCookies(username,account));
            */
            response.setHeader("Host","m.damai.cn");
            response.sendRedirect("http://m.damai.cn/damai/trade/index.html?"+data);
        }catch (Exception e){
            e.printStackTrace();
        }
    }


    /**
     *
     */
    @RequestMapping(value = "/auto/all", method = RequestMethod.GET)
    public void autoALL(HttpServletResponse response,Long orderId,String token) {
        System.out.println(token);
        System.out.println(orderId);
        if(token==null || jwtTokenUtil.isTokenExpired(token)) {
            throw new BaseException(BizExceptionEnum.TOKEN_ERROR);
        }
        String username = jwtTokenUtil.getUsernameFromToken(token);
        ConcurrentHashMap<Long, VocalBean> ordersMap = GlobalCache.user_vocal.get(username);
        System.out.println("当前登录用户:"+username);
        System.out.println("当前map:"+ordersMap.toString()+";"+ordersMap.size());
        VocalBean vocalBean = ordersMap.get(orderId);
        if(vocalBean == null){
            throw new BaseException(BizExceptionEnum.AUTH_COOKIE_ERROR);
        }
        String vocalId = vocalBean.getProjectId();
        String proId = vocalBean.getPriceId();
        String companyId = vocalBean.getCompanyId();
        String performId = vocalBean.getPerformId();

        String info = CrawlerUtil.getInfo(vocalId);
        JSONObject jsonObj = JSONObject.parseObject(info);
        JSONObject jsonData = (JSONObject) jsonObj.get("Data");
        JSONArray performs = (JSONArray)jsonData.get("performs");
        JSONObject perform = null;
        long time = new Date().getTime() + 302000;
        for (Object good:
        performs) {
            perform = (JSONObject)good;
            new TicketThread(vocalId,perform.get("PerformID").toString(),username).start();
        }

        while (true){
            long now = new Date().getTime();
            if(now >= time  ){
                return;
            }
            ConcurrentHashMap<String, String> userMap = GlobalCache.user_auto_all.get(username);
            if(userMap !=null && userMap.size()>=0 ){
                String p = userMap.get(vocalId);
                if(StringUtils.isNotEmpty(p)){
                    try{
                        //companyId = CrawlerUtil.getCompanyId(vocalId);
                        String data = "commodity=2|"+proId+"^"+1+"^"+performId+"&cityId="+companyId+"&projectId="+vocalId+"&privilegeId=0"+"&spm=a2o71.selectitem.bottom.dselectsubmit";
                        response.setHeader("Host","m.damai.cn");
                        response.sendRedirect("http://m.damai.cn/damai/trade/index.html?"+data);
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        }





    }
    public String getLoginUserName(HttpServletRequest request){
        final String requestHeader = request.getHeader(jwtProperties.getHeader());
        String authToken = requestHeader.substring(7);
        return jwtTokenUtil.getUsernameFromToken(authToken);
    }

    public String getCookies(String username,String account){
        ConcurrentHashMap<String, CookieStore> loginCookieMap = GlobalCache.user_login_cookies.get(username);
        CookieStore cookieStore = loginCookieMap.get(account);
        String cookieStr="";
        for (org.apache.http.cookie.Cookie cookie:
                cookieStore.getCookies()) {
            cookieStr+=(cookie.getName()+"="+cookie.getValue()+";");
        }
        return cookieStr;
    }

}
